<?php
/* 
 * ebiz front
 * 
 * CategoryService Service
 * 
 * @author allen
 * 
 */
require_once '../app/core/services/BaseService.php';
require_once '../app/models/ProductDao.php';
require_once '../app/models/ProductItemDao.php';
require_once '../app/models/ProductImagesDao.php';
require_once '../app/models/ShoppingCartDao.php';
require_once '../app/models/DeliveryInfoDao.php';

class ShoppingcartService extends BaseService 
{
    private $productDao;
    private $productItemDao;
    private $productImageDao;
    private $shoppingCartDao;
    private $deliveryInfoDao;
	
    public function __construct(){
        parent::__construct();
        $this->productDao = new ProductDao($this->dbUtil);
        $this->productItemDao = new ProductItemDao($this->dbUtil);
        $this->productImageDao = new ProductImagesDao($this->dbUtil);
        $this->shoppingCartDao = new ShoppingCartDao($this->dbUtil);
        $this->deliveryInfoDao = new DeliveryInfoDao($this->dbUtil);
    }
    
    public function getShoppingcartInfoByCustomerId($customerId){   //used in cart function of utility controller 
    	$iteminfos = $this->productItemDao->getShoppingcartInfoByCustomerId($customerId);
        return $iteminfos;    	
    }
    
    public function getItemIdsByItemInfo($itemInfo){
    	$itemIds = "";
    	foreach ($itemInfo as $item) {
    		$itemIds .= $item['product_item_id'].",";
    	}
    	$len = strlen($itemIds);
    	$itemIds = substr($itemIds, 0, $len-1);
    	return $itemIds;
    }
    
    public function deleteShoppingCartInfo($scId){   //used in postController
    	$result = array();
    	$result = $this->shoppingCartDao->deleteShoppingCartById($scId);
    	return $result;
    }

    public function updateQuantityByItemid($customerId, $pItemId, $quantity){    //used in postController
    	$result = array();
        $result = $this->shoppingCartDao->updateQuantityByItemid($customerId, $pItemId, $quantity);
        return $result;
    }
    
    public function showItemAndTotalByCustomerId($cid){     //used in header view to show the item and total info
    	$result = array();
    	$result = $this->shoppingCartDao->getPriceAndQuantityByCustomerId($cid);
        $items = 0;
        $total = 0;
        $productResult = array();
        foreach ($result as $item) {
            $items += $item['quantity'];
            $total += $item['sale_price'] * $item['quantity'];
            $productInfo = $this->productDao->getByProductId($item['pid']);
            $productResult[] = array('title' => CommonUtil::cut_str($productInfo[0]["title"], 20, 0), 
                                     'sale_price' => $item['sale_price'],
                                     'quantity' => $item['quantity']
                                        );
        }
        $result = array($items, $total, "item_info" => $productResult);
	    return $result;
    }
    
    public function addShoppingCart($param){   //used in postController
    	$this->shoppingCartDao->saveShoppingCart($param);
    }
    
    public function shoppingCartIsExist($itemId, $cid){
    	$resule = $this->shoppingCartDao->getShoppingCartByItemIdAndCid($itemId, $cid);
    	if(empty($resule)){ //do not have this customer
//    		echo "false <hr>";
    		return false;
    	}else{     //have the customer , and this customer already buy some goods
//    		echo "true <hr>";
    		return true;
    	}
    }
    
    public function addQuantityByCidItemid($customerId, $pItemId, $quantity){   //used in postController
        $result = array();
        $result = $this->shoppingCartDao->addQuantityByItemid($customerId, $pItemId, $quantity);
        return $result;
    }
    
    public function saveToCookie($param){   //used in postController
    	$productItemId = $param['productItemId'];
    	$quantity = $param['quantity'];
    	$salePrice = $param['salePrice'];
    	$cart = isset($_COOKIE['cart']) ? $_COOKIE['cart'] : "";
    	if($cart != ""){
            foreach($cart as $key => $value){
                if($key == $productItemId){
                    $have = $key;
                    $cartcount = $value['quantity'];
                }
            }
        }
        if(!empty($have)){
            setcookie("cart[$have][quantity]", $cartcount + $quantity, time() + 3600*24, '/');
        }else{
            setcookie("cart[$productItemId][quantity]", $quantity, time() + 3600*24, '/');
            setcookie("cart[$productItemId][salePrice]", $salePrice, time() + 3600*24, '/');
        }
        
    }
    
    public function getShoppingCartInfoFromCookie(){    //used in utilityController
    	$cart = isset($_COOKIE['cart']) ? $_COOKIE['cart'] : "";
        $iteminfos = array();
        if(empty($cart)){
        	return null;
        }
        foreach ($cart as $key => $itemCookie) {
            $productItemId = $key;
            $quantity = $itemCookie['quantity'];
            $item = $this->productItemDao->getShoppingCartInfoByItemId($productItemId);
            foreach ($item as $upc) {
            	$iteminfos[] = array("pItemId" => $upc['pItemId'],
            	                   "url_title" => $upc['url_title'],
            	                   "attribute_1" => $upc['attribute_1'],
            	                   "value_1" => $upc['value_1'],
            	                   "attribute_2" => $upc['attribute_2'],
            	                   "value_2" => $upc['value_2'],
            	                   "attribute_3" => $upc['attribute_3'],
            	                   "value_3" => $upc['value_3'],
            	                   "attribute_4" => $upc['attribute_4'],
            	                   "value_4" => $upc['value_4'],
            	                   "attribute_5" => $upc['attribute_5'],
            	                   "value_5" => $upc['value_5'],
            	                   "sale_price" => $upc['sale_price'],
            	                   "title" => $upc['title'],
            	                   "name" => $upc['name'],
            	                   "folder" => $upc['folder'],
            	                   "quantity" => $quantity,
            	                   "upc" => $upc['upc']
            	                   );
            }
        }
        return $iteminfos;    
    }
    
    public function showItemAndTotalFromCookie(){   //used in header View
        $items = 0;
        $total = 0;
        $productResult = array();
    	$cart = isset($_COOKIE['cart']) ? $_COOKIE['cart'] : null;
//        if($cart != null){    
    	if(!empty($cart)){    
            foreach ($cart as $itemId => $item) {
                $items += $item['quantity'];
                $total += $item['salePrice'] * $item['quantity'];
                $itemInfo = $this->productItemDao->getById($itemId);
                $pid = $itemInfo[0]["product_id"];
                $productInfo = $this->productDao->getByProductId($pid);
	            $productResult[] = array('title' => CommonUtil::cut_str($productInfo[0]["title"], 20, 0), 
                                     'sale_price' => $item['salePrice'],
                                     'quantity' => $item['quantity']
                                        );
            }
            $param = array($items, $total, "item_info" => $productResult);
            return $param;
        }
        return null;
    }
    
    public function combineShoppingCart($customerId){   //used in postController to combine cookie value to DB
    	$cart = isset($_COOKIE['cart']) ? $_COOKIE['cart'] : null ;
    	if(!empty($cart)){
            foreach ($cart as $itemId => $value) {
                $quantity = $value['quantity'];
                $salePrice = $value['salePrice'];
                if(self::shoppingCartIsExist($itemId, $customerId)){ //this item is exist , only update the quantity     
	                self::addQuantityByCidItemid($customerId, $itemId, $quantity);
	            }else{  //this item is not exist , add a new one
	                $result = $this->productItemDao->getById($itemId);
	            	$productId = $result[0]['product_id'];
	            	$param = array($productId, $itemId, $customerId, $quantity, $salePrice);
	            	self::addShoppingCart($param);  //insert into value to shopping_carts table
	            }
//                delete cookie value
                setcookie("cart[$itemId][quantity]", "", time() - 3600*24, '/');
                setcookie("cart[$itemId][salePrice]", "", time() - 3600*24, '/');
            }
    	}
    }
    
    public function updateStateById($customerId, $pItemId, $quantity){
        $itemInfo = $this->productItemDao->getById($pItemId);
    	$inventory = $itemInfo[0]['inventory'];
    	if($inventory < $quantity){
    		$quantity = $inventory;
    	}
    	$result = array();
        $result = $this->shoppingCartDao->updateStateById($customerId, $pItemId, $quantity);
        return $result;
    }
    
    public function updateStateForClearById($customerId){ //clear the shoppingCart status equal 0 by customerId    
        $result = array();
        $result = $this->shoppingCartDao->updateStateForClearById($customerId);
        return $result;
    }
    
    public function getShoppingcartInfoToCheckoutByCustomerId($customerId){   //used in cart function of utility controller 
        $iteminfos = $this->shoppingCartDao->getShoppingcartInfoToCheckoutByCustomerId($customerId);
        return $iteminfos;      
    }
    
    public function getAddressByCustomerId($customerId){
    	$address = $this->deliveryInfoDao->getAddressByCid($customerId);
    	return $address;
    }
    
    /**
     * judge the user bought quantity if less than inventity of DB,if more than DB then return false,user can not to buy
     */
//    public function getItemQtyInfo($itemIds, $qtyArray, $customerId){
    public function getItemQtyInfo($itemIdArray, $qtyArray, $scIdArray){
    	$result = array();
        //$itemInfoArray = $this->productItemDao->getItemInfoByItemIds($itemIds); //get all item info//query productitem table not use cid    
        for($i = 0; $i < count($itemIdArray); $i++){
        	$itemInfoArray = $this->productItemDao->getItemInfoByItemIds($itemIdArray[$i]);
        	if($itemInfoArray[0]['piIsDelete'] != 0 || $itemInfoArray[0]['pIsDelete'] != 0){ //this item is already deleted
        		$result[] = array("itemId" => $itemInfoArray[0]['pItemId'],
//        		                  "scId" => $itemInfoArray[$i]['scId'],
        		                  "title" => $itemInfoArray[0]['title'],
        		                  "attr1" => $itemInfoArray[0]['attribute_1'],
        		                  "value1" => $itemInfoArray[0]['value_1'],
        		                  "attr2" => $itemInfoArray[0]['attribute_2'],
        		                  "value2" => $itemInfoArray[0]['value_2'],
        		                  "error" => "delete"
        		                  );
        	}else{
        		if($itemInfoArray[0]['inventory'] == 0){
	                $result[] = array("itemId" => $itemInfoArray[0]['pItemId'],
//                                      "scId" => $itemInfoArray[$i]['scId'],
	                                  "title" => $itemInfoArray[0]['title'],
	                                  "attr1" => $itemInfoArray[0]['attribute_1'],
	                                  "value1" => $itemInfoArray[0]['value_1'],
	                                  "attr2" => $itemInfoArray[0]['attribute_2'],
	                                  "value2" => $itemInfoArray[0]['value_2'],
	                                  "error" => "none"
	                                  );
//                    delete the item info from shoppingcart table by customer id and item id//move to getItemQtyInfo function
                    $this->shoppingCartDao->deleteShoppingCartById($scIdArray[$i]);
                }else if($itemInfoArray[0]['inventory'] < $qtyArray[$i]){
	                $result[] = array("itemId" => $itemInfoArray[0]['pItemId'],
//                                      "scId" => $itemInfoArray[$i]['scId'],
	                                  "title" => $itemInfoArray[0]['title'],
	                                  "attr1" => $itemInfoArray[0]['attribute_1'],
	                                  "value1" => $itemInfoArray[0]['value_1'],
	                                  "attr2" => $itemInfoArray[0]['attribute_2'],
	                                  "value2" => $itemInfoArray[0]['value_2'],
	                                  "error" => $itemInfoArray[0]['inventory']
	                                  );
                }else if($itemInfoArray[0]['sale_price'] <= 0){
	                $result[] = array("itemId" => $itemInfoArray[0]['pItemId'],
//                                      "scId" => $itemInfoArray[$i]['scId'],
	                                  "title" => $itemInfoArray[0]['title'],
	                                  "attr1" => $itemInfoArray[0]['attribute_1'],
	                                  "value1" => $itemInfoArray[0]['value_1'],
	                                  "attr2" => $itemInfoArray[0]['attribute_2'],
	                                  "value2" => $itemInfoArray[0]['value_2'],
	                                  "error" => "priceerror"
	                                  );
	            }
        	}
        }
        return $result;
    }
    
    /**
     * show the html info in shoppingcart page
     */
    public function showHtmlInfo($result){
    	require_once "../". $GLOBALS["local"] ."/"."shoppingCart.php";
    	$html = "";
    	if(isset($result) && count($result) != 0){
            foreach ($result as $item) {
	            $attr1 = "";
	            $value1 = "";
//	            $attr2 = "";
	            $value2 = "";
	            $info = "";
	            $title = $item['title'];
	            $info = $item['error'];
	            if(isset($item['attr1']) && isset($item['value1'])){
	                $attr1 = $item['attr1'];
	                $value1 = $item['value1'];
	            }
                if(isset($item['attr2']) && isset($item['value2'])){
//                    $attr2 = $item['attr2'];
                    $value2 = $item['value2'];
	            }
	            if($item['error'] == "none"){
	                $info = SHOPPINGCARTQTYEMPTYERROR;
	            }else if($item['error'] == "delete"){
	                $info = NOLONGERINSTORE;
	            }elseif($item['error'] == "priceerror"){
	            	$info = PRICEERROR;
	            }else{
	                $info = SHOPPINGCARTQTYEMPTYERROR;
//	                ."  ".$item['error'];
	            }
//	            $scId = $item['scId'];
//                if(empty($attr1) || empty($value1)){
                    $html .=  "<div>$title : <strong style='color: rgb(17, 17, 17);'> $info </strong></div>";
//                }else{
//                    $html .=  "<div>$title ( $value1  $value2 ) : <strong style='color: rgb(17, 17, 17);'> $info </strong></div>";
//                }
	        }
    	}
    	return $html;
    }
    
    /**
     * show the price info
     */
    public function showPriceHtmlInfo($result){
    	$html = "";
    	if(isset($result) && count($result) != 0){
            foreach ($result as $item) {
	            $title = $item['title'];
	            $DBSalePrice = $item['db_sale_price'];
	            //$salePrice = $item['sale_price'];
                $html .=  "<div>$title : <strong style='color: rgb(17, 17, 17);'> $DBSalePrice </strong></div>";
	        }
    	}
    	return $html;
    }
    
	
   
}

